package com.credithc.customers.base.utils;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


public class TokenUtils {
    //私钥
    public static String SECRET = "YZTAUTH";
    //过期时间 1h
    private static final long EXPIRE_TIME = 60 * 60 * 1000;

    public static String createToken(String code,String type) throws Exception {
        //签发时间
        Date istDate = new Date();
        // 设置过期时间
        Date expiresDate = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");

        String token = JWT.create()
                .withHeader(map)
                .withClaim("code", code)
                .withClaim("type", type)
//                .withExpiresAt(expiresDate)
//                .withIssuedAt(istDate)
                .sign(Algorithm.HMAC256(SECRET));

        return token;
    }


    public static Map<String, Claim> verifyToken(String token) throws Exception{
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        DecodedJWT jwt = null;
        try {
            jwt = verifier.verify(token);
        } catch (Exception e) {
            throw new RuntimeException("凭证过期！");
        }

        return jwt.getClaims();
    }



    public static void main(String[] args) throws Exception {
        String code = "f7c31a1dabca4753b654acc184148e59";
        String token = createToken(code,"refreshToken");
        System.out.println("code="+code);
        System.out.println("token="+token);
        //正常测试
        Map<String, Claim> verifyToken = verifyToken(token);
        String asString = verifyToken.get("code").asString();
        System.out.println(asString);

        //过期测试
        token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjb2RlIjoiMTg0ODZlNjQ2YzNiNDZkNWI0ZGM2ZWE4ZDZhMjdmYTgifQ.blJEXpqFFlexROLofJMe6pBwjW-WdcS6W8k2vOw0QHQ";
        Map<String, Claim> verifyToken2 = verifyToken(token);
    }


    /**
     * 生成唯一标识
     * @return
     */
    private final static String getUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

}

